import shutil
import subprocess
import sys

with open('ahk/templates/daemon.ahk') as f:
    daemon_script = f.read()

with open('ahk/templates/hotkeys.ahk') as hotkeyfile:
    hotkey_script = hotkeyfile.read()

with open('ahk/templates/daemon-v2.ahk') as fv2:
    daemon_script_v2 = fv2.read()

with open('ahk/templates/hotkeys-v2.ahk') as hotkeyfilev2:
    hotkey_script_v2 = hotkeyfilev2.read()

GIT_EXECUTABLE = shutil.which('git')

if not GIT_EXECUTABLE:
    raise RuntimeError('git executable not found')

new_contents = f'''\
# THIS FILE IS AUTOGENERATED BY _set_constants.py
# DO NOT EDIT BY HAND

DAEMON_SCRIPT_TEMPLATE = r"""{daemon_script}
"""

HOTKEYS_SCRIPT_TEMPLATE = r"""{hotkey_script}
"""

DAEMON_SCRIPT_V2_TEMPLATE = r"""{daemon_script_v2}
"""

HOTKEYS_SCRIPT_V2_TEMPLATE = r"""{hotkey_script_v2}
"""
'''

with open('ahk/_constants.py', encoding='utf-8') as f:
    constants_text = f.read()

if constants_text != new_contents:
    with open('ahk/_constants.py', 'w', encoding='utf-8') as f:
        f.write(new_contents)
    print('MODIFIED _constants.py', file=sys.stderr)
    subprocess.run([GIT_EXECUTABLE, 'add', '--intent-to-add', 'ahk/_constants.py'])
    raise SystemExit(1)
else:
    raise SystemExit(0)
